<template>
  <div class="bar-charts-com">
    <div class="chart" ref="chart">

    </div>
  </div>
</template>
<script>
import * as echarts from 'echarts'
import {getRandomColor, hexToHexWithAlpha} from "@/utils/constant";

/**
 * @description 饼图组件
 * source 数据源 [{name:'',value:0},{name:'',value:0}]
 * size 百分比 单个数字为 饼图 代表饼图直径，数组为环形图 数组第一个值为内径，第二个值为外径
 * center 百分比 第一个值为X方向偏移 第二个值为Y方向偏移
 * radius 环形图时每一块的圆角
 * alpha 颜色透明度 0-100
 * padAngle 每一扇之间的间距
 */
export default {
  name: 'PieCharts',
  props: {
    source: {
      type: Array,
      required: true,
    },
    loading: {
      type: Boolean,
      default: true
    },
    size:{
      type:[Number,Array],
      default:70
    },
    center:{
      type:Array,
      default:()=>{
        return[50,50]
      }
    },
    radius: {
      type: Number,
      default:5,
    },
    alpha: {
      type: Number,
      default: 100
    },
    padAngle: {
      type: Number,
      default: 0
    }
  },
  watch: {
    source: {
      deep: true,
      immediate: true,
      handler(val) {
        this.$nextTick(() => {
          if (val && val.length) {
            const option = this.getOption();
            this.getChart()
            this.chart.setOption(option)
          }
        })
      }
    },
    loading: {
      immediate: true,
      handler(val) {
        this.$nextTick(() => {
          this.getChart()
          if (val) {
            this.chart.showLoading({
              text: '加载中',
              textColor: '#fff',
              maskColor: 'rgba(0,0,0,0)'
            })
          } else {
            this.chart.hideLoading()
          }
        })
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  methods: {
    getChart() {
      this.chart = this.chart || echarts.init(this.$refs.chart)
    },
    getOption() {
      const color = getRandomColor(this.source.length)
      return {
        color: color.map(item => hexToHexWithAlpha(item, this.alpha)),
        series: [{
          type: 'pie',
          radius: Array.isArray(this.size) ? this.size.map(item => `${item}%`) : this.size + '%',
          center: this.center.map(item => `${item}%`),
          data: this.source,
          padAngle: this.padAngle,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            show: true,
            formatter: '{b}：{d}%',
            color: '#fff'
          },
          itemStyle: {
            borderRadius: this.radius + 'px'
          }
        }],
        tooltip: {
          trigger: 'axis'
        }
      }
    }
  },
  beforeDestroy() {
    this.chart && this.chart.dispose();
    this.chart = null
  }
}
</script>
<style lang="scss" scoped>
.bar-charts-com {
  width: 100%;
  height: 100%;

  .chart {
    width: 100%;
    height: 100%;
  }
}
</style>
